package com.fancy.learncenter.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.AddDiscussDataBean;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.DiscussDataBean;
import com.fancy.learncenter.bean.MedioDataBean;
import com.fancy.learncenter.bean.PraiseDataBean;
import com.fancy.learncenter.bean.ShareDataBean;
import com.fancy.learncenter.common.AudioPlayer;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.Player;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.activity.base.MallCommonH5Activity;
import com.fancy.learncenter.ui.adapter.FragmentPlayAuidoDiscussAdapter;
import com.fancy.learncenter.ui.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.ui.adapter.base.CustomViewHold;
import com.fancy.learncenter.ui.view.SharePopupWindow;
import com.fancy.learncenter.utils.DataUtil;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.utils.WXShareUtil;
import com.nineoldandroids.animation.ObjectAnimator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 音频播放
 */
public class PlayAudioActivity extends BaseActivity implements View.OnTouchListener {
    TextView tvAudioTotalTime;
    TextView tvAudioRunTime;
    SeekBar sbAudio;
    SimpleDraweeView showIcon;
    SimpleDraweeView showGg;
    RelativeLayout topView;
    //    RecyclerView imgList;
    SimpleDraweeView headerIcon;
    TextView headerName;
    TextView headerIntro;
    TextView content;
    FragmentPlayAuidoDiscussAdapter discussAdapter;

    ObjectAnimator animation;
//    AudioPlayer audioPlayer;

    //封面图
    String showResourceCoverImg = "";
    // 播放列表
    String playLink = "";
    //  资源名称
    String showResourceName = "";
    //  资源ID
    int showResourceId = 0;

    SharePopupWindow sharePopupWindow;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.right_img)
    ImageView rightImg;
    @Bind(R.id.isPraise)
    ImageView isPraise;
    @Bind(R.id.praise_num)
    TextView praiseNum;
    @Bind(R.id.praise)
    LinearLayout praise;
    @Bind(R.id.shop_cart)
    LinearLayout shopCart;
    @Bind(R.id.discuss)
    LinearLayout discuss;
    @Bind(R.id.rootView)
    LinearLayout rootView;
    @Bind(R.id.dicuss)
    EditText dicuss;
    @Bind(R.id.send)
    TextView send;
    @Bind(R.id.dis_ll)
    LinearLayout disLl;
    @Bind(R.id.shop_cart_text)
    TextView shopCartText;
    @Bind(R.id.shop_cart_image)
    ImageView shopCartImage;
    @Bind(R.id.back_image)
    ImageView backImage;
    @Bind(R.id.title)
    TextView title;

    float oldY = 0;
    float nowY = 0;

//    ArrayList<MedioDataBean.DetailBean.ResourceVOListBean> imgsData;
//    ImgsAdatapter imgsAdapter;

    String buyUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_audio, Status.STATUS);
        ButterKnife.bind(this);
//        showResourceCoverImg = getIntent().getStringExtra(Constant.showResourceCoverImg);
        showResourceId = getIntent().getIntExtra("showResourceId", 0);
//        playLink = getIntent().getStringExtra(Constant.playLink);
        showResourceName = getIntent().getStringExtra(Constant.showResourceName);
//        initToolbar(showResourceName);
        title.setText(showResourceName);
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });


        initView();
        getDetailData();
        initDiscuss();
        addPV();
        st = new CircleThread();
        th = new Thread(st);
    }

    CircleThread st;
    CircleThread ch;
    Thread th;
    Player player;

//    private void iniData() {
//
//        initDiscuss();
//
//
//    }


    private void initPlayer() {
        animation = ObjectAnimator.ofFloat(showIcon, "rotation", 0, 360);
        animation.setRepeatCount(-1);
        animation.setDuration(5000);
        LinearInterpolator lin = new LinearInterpolator();//设置动画匀速运动
        animation.setInterpolator(lin);

        player = new Player(sbAudio, tvAudioRunTime, tvAudioTotalTime);
        LogUtil.MyLog("playLink", "========playLink==="+playLink);
        player.playUrl(playLink);
        player.setPlayerStatus(new Player.PlayerStatus() {
            @Override
            public void playStart() {


            }

            @Override
            public void playEnd() {
                LogUtil.MyLog("playEnd", "========playEnd===");
                currentPlayTime = animation.getCurrentPlayTime();
                animation.cancel();

                st.stopThread();
            }
        });
    }

    private void initDiscuss() {
        ArrayList data = new ArrayList();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        discussAdapter = new FragmentPlayAuidoDiscussAdapter(this, data);
        recyclerView.setAdapter(discussAdapter);
        discussAdapter.setHeaderView(topView, recyclerView);
    }

    //动画当初所转动的时间
    private long currentPlayTime;


    private void initView() {
        topView = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.activity_paly_audio_top, null);
        tvAudioTotalTime = (TextView) topView.findViewById(R.id.tv_audio_total_time);
        tvAudioRunTime = (TextView) topView.findViewById(R.id.tv_audio_run_time);
        sbAudio = (SeekBar) topView.findViewById(R.id.sb_audio);
        showIcon = (SimpleDraweeView) topView.findViewById(R.id.show_icon);
        showGg = (SimpleDraweeView) topView.findViewById(R.id.show_bg);

        headerIcon = (SimpleDraweeView) topView.findViewById(R.id.headerIcon);
        headerIntro = (TextView) topView.findViewById(R.id.headerIntro);
        headerName = (TextView) topView.findViewById(R.id.headerName);
        content = (TextView) topView.findViewById(R.id.content);

        recyclerView.setOnTouchListener(this);
        showIcon.setClickable(false); //初始化不让点击
        showIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!player.mediaPlayer.isPlaying()) {
                    player.play();
//                    animation.setCurrentPlayTime(currentPlayTime);
//                    animation.start();


                    if (isStart) {
                        try {
                            th.start();
                        } catch (IllegalThreadStateException e) {
                        }
                    } else {
                        th = new Thread(st);
                        th.start();
                        isStart = true;
                    }
                } else {
                    player.pause();
//                    currentPlayTime = animation.getCurrentPlayTime();
//                    animation.cancel();
//                    isStart = false;
//                    thread = new Thread(ch);
//                    thread.start();

                    st.stopThread();
                }
            }
        });
        rightImg.setImageResource(R.mipmap.share);
        rightImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (sharePopupWindow == null) {
                    sharePopupWindow = new SharePopupWindow(PlayAudioActivity.this, rootView);
                    sharePopupWindow.setShareCallBack(new SharePopupWindow.ShareCallBack() {
                        @Override
                        public void wxCallBack() {
                            if (shareVOBean != null) {
                                String urlPic = shareVOBean.getImageUrl();
                                String title = shareVOBean.getTitle();
                                String content = shareVOBean.getSubTitle();
                                String linkYrl = shareVOBean.getUrl();
                                WXShareUtil.getInstance(PlayAudioActivity.this).shareWebPage(urlPic, title, content, linkYrl, false);
                            } else {
                                getShareData(false);
                            }
                        }

                        @Override
                        public void wxFriendCallBack() {
                            if (shareVOBean != null) {
                                String urlPic = shareVOBean.getImageUrl();
                                String title = shareVOBean.getTitle();
                                String content = shareVOBean.getSubTitle();
                                String linkYrl = shareVOBean.getUrl();
                                WXShareUtil.getInstance(PlayAudioActivity.this).shareWebPage(urlPic, title, content, linkYrl, true);
                            } else {
                                getShareData(true);
                            }
                        }
                    });
                }
                sharePopupWindow.showPopupWindow();
            }
        });
//        setRightImg(R.mipmap.share, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
    }

    /**
     * 滑动隐藏输入框
     *
     * @param v
     * @param event
     * @return
     */

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                oldY = event.getY();
                Log.i("oldY", oldY + "");
                break;
            case MotionEvent.ACTION_MOVE:
                nowY = event.getY();
                Log.i("nowY", nowY + "");
                break;
            case MotionEvent.ACTION_UP:
                Log.i("abs", Math.abs(oldY - nowY) + "");
                if (Math.abs(oldY - nowY) > 50) {
                    showSoftInputFromWindow(false);
                    disLl.setVisibility(View.GONE);
                }
                break;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        if (disLl.getVisibility() == View.VISIBLE) {
            disLl.setVisibility(View.GONE);
            showSoftInputFromWindow(false);
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void finish() {
        animation.clone();
        player.stop();
        st.stopThread();
        super.finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        currentPlayTime = animation.getCurrentPlayTime();
        animation.cancel();
        player.pause();
        st.stopThread();
    }

    @OnClick({R.id.praise, R.id.discuss, R.id.shop_cart, R.id.send, R.id.record})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.send:
                if (!TextUtils.isEmpty(dicuss.getText().toString().trim())) {
                    addComment(dicuss.getText().toString());
                } else {
                    ToastUtil.show("评论不能为空");
                }
                break;
            case R.id.praise:
                addPraiseNum();
                break;
            case R.id.discuss:
                disLl.setVisibility(View.VISIBLE);
                showSoftInputFromWindow(true);
                break;
            case R.id.shop_cart:

                if (!TextUtils.isEmpty(buyUrl)) {
                    intent = new Intent(this, MallCommonH5Activity.class);
                    intent.putExtra(MallCommonH5Activity.URL_KEY, buyUrl);
                    startActivity(intent);
                } else {
//                    ToastUtil.show("暂无购买商品");
                }

                break;
            case R.id.record:
                if (Constant.isLogin) {
                    intent = new Intent(this, RecorderActivity.class);
                    intent.putExtra(Constant.showResourceCoverImg, showResourceCoverImg);
                    intent.putExtra(Constant.showResourceName, showResourceName);
                    startActivity(intent);
                } else {

                    Intent intentLogin = new Intent(this, LoginActivity.class);
                    startActivity(intentLogin);
                }
                break;
        }
    }


    private void getDetailData() {
        HttpMehtod.getInstance().getMedioDetail(showResourceId, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<MedioDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), MedioDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<MedioDataBean>() {
                    @Override
                    public void success(MedioDataBean dataBean) {
                        headerIcon.setImageURI(dataBean.getDetail().getRecordImg());
                        headerName.setText(dataBean.getDetail().getRecordName());
                        headerIntro.setText(dataBean.getDetail().getRecordIntro());
                        content.setText(dataBean.getDetail().getIntro());

                        buyUrl = dataBean.getDetail().getBuyUrl();
                        showResourceCoverImg = dataBean.getDetail().getWholeShowResourceCoverImg();
                        playLink = dataBean.getDetail().getWholePlayLink();


                        if (TextUtils.isEmpty(buyUrl)) {
                            shopCartImage.getDrawable().setAlpha(127);
                            shopCartText.setAlpha(0.5f);
                        } else {
                            shopCartImage.getDrawable().setAlpha(255);
                            shopCartText.setAlpha(1f);
                        }

                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();
            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                showIcon.setImageURI(showResourceCoverImg);
                showGg.setImageURI(showResourceCoverImg);
                initPlayer();
                showIcon.setClickable(true);

            }
        });


        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);
        HttpMehtod.getInstance().getPraiseNum(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<PraiseDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), PraiseDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<PraiseDataBean>() {
                    @Override
                    public void success(PraiseDataBean dataBean) {
                        if (dataBean.getMPraiseVO().getIsHadPraise() == 1) {
                            isPraise.setImageResource(R.mipmap.like);

                            praise.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                        }
                        if (!TextUtils.isEmpty(dataBean.getMPraiseVO().getPraiseNums())) {
                            praiseNum.setText(dataBean.getMPraiseVO().getPraiseNums());
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });

        getDiscuss();
    }


    private void addPraiseNum() {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);

        HttpMehtod.getInstance().addPraiseNum(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<PraiseDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), PraiseDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<PraiseDataBean>() {
                    @Override
                    public void success(PraiseDataBean dataBean) {
                        if (dataBean.getMPraiseVO().getIsHadPraise() == 1) {
                            isPraise.setImageResource(R.mipmap.like);

                            praise.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                        }
                        praiseNum.setText(dataBean.getMPraiseVO().getPraiseNums());

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    private void getDiscuss() {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);
        HttpMehtod.getInstance().getDiscuss(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<DiscussDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), DiscussDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<DiscussDataBean>() {
                    @Override
                    public void success(DiscussDataBean dataBean) {
                        discussAdapter.notifyDataSetChanged(dataBean.getCommentsVOList());
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    private void addComment(String content) {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);
        map.put("content", content);

        HttpMehtod.getInstance().addComment(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<AddDiscussDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), AddDiscussDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<AddDiscussDataBean>() {
                    @Override
                    public void success(AddDiscussDataBean dataBean) {
                        if (dataBean.getResult() == 1) {
                            disLl.setVisibility(View.GONE);
                            showSoftInputFromWindow(false);
                            dicuss.setText("");
                            ToastUtil.show("评论成功");

                            getDiscuss();
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    ShareDataBean.ShareVOBean shareVOBean;

    private void getShareData(final boolean isFirend) {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("shareType", 1);

        HttpMehtod.getInstance().getShareData(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<ShareDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), ShareDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<ShareDataBean>() {
                    @Override
                    public void success(ShareDataBean dataBean) {
                        shareVOBean = dataBean.getShareVO();
                        String urlPic = shareVOBean.getImageUrl();
                        String title = shareVOBean.getTitle();
                        String content = shareVOBean.getSubTitle();
                        String linkYrl = shareVOBean.getUrl();
                        WXShareUtil.getInstance(PlayAudioActivity.this).shareWebPage(urlPic, title, content, linkYrl, isFirend);
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }


    /**
     * EditText获取焦点并显示软键盘
     */
    public void showSoftInputFromWindow(boolean isShow) {
        dicuss.setFocusable(true);
        dicuss.setFocusableInTouchMode(true);
        dicuss.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isShow) {
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        } else {
            imm.hideSoftInputFromWindow(dicuss.getWindowToken(), 0); //强制隐藏键盘
        }
    }

    private void addPV() {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);
        HttpMehtod.getInstance().addPV(map, new CustomNetSubscriber(this, false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
            }
        });
    }

    boolean isStart = true;

    private class CircleThread implements Runnable {

        public void stopThread() {
            isStart = false;
        }

        @Override
        public void run() {
            while (isStart) {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
                try {
                    Thread.sleep(5);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                showIcon.setRotation((float) (showIcon.getRotation() + 0.2));
            }
            super.handleMessage(msg);
        }
    };
}
